package com.heima.utils.baidu;

import com.alibaba.fastjson.JSONArray;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 获取token
 *
 * @author rookie001
 * @creat 2023-06-10-19:28
 */
public class SampleToken {

    public static String getToken() {
        try {
            OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();


            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token?" +
                            "client_id=SFNzUulLyAVwWGztGEYChcoB" +
                            "&client_secret=qdY1Pa61pjUqhTzFIiuxlpiZMmQxjDp9" +
                            "&grant_type=client_credentials")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            String responseStr = response.body().string();
            String numStr = StringUtils.substringAfter(StringUtils.substringBefore(responseStr, ","), ":");
            System.out.println(numStr);
            return numStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static ResponseResult TextCenor(String token, String text){
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
        try {
            String param = "text=" + URLEncoder.encode(text, "utf-8");

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = token;

            String result = HttpUtil.post(url, accessToken, param);
          return  ResponseResult.okResult(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

}
